package com.lvmama.config;

import com.lvmama.config.common.Constant;
import com.lvmama.config.test.TestRollbackThread;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;

/**
 * Created by troy on 2016/7/18.
 * kouhongyu@163.com
 */
public class ZooKeeperPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private final static Log LOG = LogFactory.getLog(ZooKeeperPropertyPlaceholderConfigurer.class);

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        try {
            fillCustomProperties(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.processProperties(beanFactoryToProcess, props);

        /**
         * todo troy 临时
         */
//        Thread test = new Thread(new TestRollbackThread());
//        test.start();
    }

    private void fillCustomProperties(Properties props) throws Exception {

        if (StringUtils.isNotBlank(props.getProperty(Constant.ZOOKEEPER_CONFIG_ADDRESS)) &&
                StringUtils.isNotBlank(props.getProperty(Constant.ZOOKEEPER_CONFIG_OWNER)) &&
                StringUtils.isNotBlank(props.getProperty(Constant.APPLICATION_NAME))) {

            ZooKeeperConfigInit configInit = new ZooKeeperConfigInit();
            Properties initProps = configInit.getProperties(props);
            if (initProps != null) {
                for (Object key : initProps.keySet()) {
                    props.put(key, initProps.get(key));
                }
            }
        } else {
            if (StringUtils.isBlank(props.getProperty(Constant.ZOOKEEPER_CONFIG_ADDRESS))) {
                LOG.warn("Can't find ZOOKEEPER_CONFIG_ADDRESS");
            }
            if (StringUtils.isBlank(props.getProperty(Constant.ZOOKEEPER_CONFIG_OWNER))) {
                LOG.warn("Can't find ZOOKEEPER_CONFIG_OWNER");
            }
            if (StringUtils.isBlank(props.getProperty(Constant.APPLICATION_NAME))) {
                LOG.warn("Can't find APPLICATION_NAME");
            }
        }
    }
}
